package com.zzy.transaction.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.zzy.transaction.context.TransactionMeta;
import com.zzy.transaction.task.TransactionTask;

import java.util.List;
import java.util.concurrent.*;

public class TransactionManager {

//    private static final ExecutorService executorService = new ThreadPoolExecutor(4, 8, 10, TimeUnit.MINUTES, new ArrayBlockingQueue<>(512));

    private static final ExecutorService executorService = Executors.newCachedThreadPool();

    public static TransactionMeta execute(ExecutorService executor, List<Runnable> tasks, long timeout, TimeUnit timeUnit) {
        try {
            if (CollectionUtil.isEmpty(tasks)) {
                TransactionMeta transactionMeta = new TransactionMeta();
                transactionMeta.afterPropertiesSet();
                transactionMeta.finish(true);
                return transactionMeta;
            }
            TransactionMeta transactionMeta = new TransactionMeta();
            transactionMeta.setTaskCount(tasks.size());
            transactionMeta.setTimeout(timeout);
            transactionMeta.setTimeUnit(timeUnit);
            TransactionCoordinator.start(transactionMeta);
            if (executor == null) {
                executor = executorService;
            }
            for (Runnable task : tasks) {
                executor.submit(TransactionTask.of(task));
            }
            return transactionMeta;
        } finally {
            TransactionCoordinator.end();
        }
    }

    /**
     * 执行任务集合
     *
     * @param tasks    任务列表
     * @param timeout  事务超时时间
     * @param timeUnit 时间单位
     * @return: com.zzy.transaction.context.TransactionMeta
     */
    public static TransactionMeta execute(List<Runnable> tasks, long timeout, TimeUnit timeUnit) {
        return execute(null, tasks, timeout, timeUnit);
    }

    public static TransactionMeta execute(List<Runnable> tasks) {
        return execute(tasks, Long.MAX_VALUE, TimeUnit.SECONDS);
    }


}
